package com.wenwei.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.orhanobut.logger.Logger;
import com.tencent.cos.utils.FileUtils;
import com.wenwei.adapter.ImageAdapter;
import com.wenwei.bean.LookSuBean;
import com.wenwei.bean.OrderInfoBean;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.R;
import com.wenwei.upload.ImageService;
import com.wenwei.upload.OssService;
import com.wenwei.upload.PauseableUploadTask;
import com.wenwei.upload.STSGetter;
import com.wenwei.utils.GlideImageLoader;
import com.wenwei.utils.RogerDateUtils;
import com.wenwei.utils.UserStringUtils;
import com.wenwei.view.GridLayoutManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by nidalee on 2017/9/23.
 */

public class PaySuccessSuActivity extends BaseActivity implements ImageAdapter.CallBack{
    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.record_address)
    TextView recordAddress;
    @Bind(R.id.record_time)
    TextView recordTime;
    @Bind(R.id.record_parking_time)
    TextView recordParkingTime;
    @Bind(R.id.input_msg_et)
    EditText inputMsgEt;
    @Bind(R.id.recycler)
    RecyclerView recycler;
    @Bind(R.id.price)
    TextView priceTv;
    @Bind(R.id.commit_btn)
    TextView commintBtn;

    private ImageAdapter mAdapter;
    private OssService ossService;
    private ImageService imageService;
    private static final String bucket = "sharepark";
    private static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_pay_success_su;
    }

    public OssService initOSS(String endpoint, String bucket) {
        //如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        //OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);

        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        credentialProvider = new STSGetter();
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(mContext, endpoint, credentialProvider, conf);
        return new OssService(oss, bucket);

    }

    private WeakReference<PauseableUploadTask> task;
    private void uploadAliImg(String name,String filePate){
        Logger.d("上传前的图片名称："+name);
        task = new WeakReference<>(ossService.asyncMultiPartUpload(name, filePate, new OssService.loadSuccessCallBack() {
            @Override
            public void loadSuccess(final String url) {
                Logger.d("上传成功"+url);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mImageList.add(url);
                        mCurrentUploadSize++;
                        Logger.d(mCurrentUploadSize+","+mImageListSize);
                        if(mCurrentUploadSize == mImageListSize){
                            //表示上传完了
                            Logger.d("上传完了呀，小逼崽子");
                            dialog.dismiss();
                            addAllege();
                        }
                    }
                });

            }
        }));
    }


    List<String> list = new ArrayList<>();
    @Override
    protected void initView() {
        super.initView();
        baseTitle.setText("申诉");


        recycler .setLayoutManager( new GridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
        recycler.setNestedScrollingEnabled(false);
        mAdapter = new ImageAdapter();
        mAdapter.setmCallBack(this);
        recycler.setAdapter(mAdapter);


        list.add("add");
        mAdapter.setmList(list);
        mAdapter.notifyDataSetChanged();

        initImage();
        ossService = initOSS(endpoint,bucket);
        imageService = new ImageService(ossService);
    }

    private void initImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.base_back, R.id.commit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finish();
                break;
            case R.id.commit_btn:

                if(inputMsgEt.getText().toString().equals("")){
                    showToast("请填写申诉内容");
                    return;
                }
                uploadImg();
                break;
        }
    }

    @Override
    public void onAddImg() {
        goActivity(this, ImageGridActivity.class, null, 99);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 99) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (ImageItem i : images) {
                    Log.d("msg", i.path);
//                    Glide.with(mContext).load(Uri.fromFile(new File(i.path))).into(headImg);
                    if(TextUtils.isEmpty(i.path)){
                        showToast("请选择图片");
                        return;
                    }
                    list.add(0,i.path);
                    mAdapter.setmList(list);
                    mAdapter.notifyDataSetChanged();

                }
            }
        }
    }

    private void initMsg(OrderInfoBean infoBean){
        recordAddress.setText(infoBean.getParkAddr());
        recordTime.setText(RogerDateUtils.getDateToHis(infoBean.getCreatedTime()));
        recordParkingTime.setText(infoBean.getParkLength()+"小时");
        priceTv.setText("¥"+infoBean.getPayTotal());
    }

    @Override
    protected void initData() {
        super.initData();
        getOrderInfo();
    }

    private BaseSubscriber<OrderInfoBean> infoSb;
    private void getOrderInfo(){
        infoSb = new BaseSubscriber<OrderInfoBean>(mContext) {
            @Override
            public void onSuccess(OrderInfoBean orderInfoBean) {
                initMsg(orderInfoBean);
            }
        };

        ApiManager.getInstance().getOrderInfo(infoSb,getIntent().getIntExtra("orderId",0));
    }



    private int mImageListSize = 0;
    private int mCurrentUploadSize = 0;
    private Random random = new Random();
    private ProgressDialog dialog;
    private void uploadImg(){

        if(list!=null&&list.size()>=2){
            mImageListSize = list.size()-1;
            if(list.size()>0){
                dialog = new ProgressDialog(mContext);
                dialog.setMessage("加载中...");
                dialog.show();
            }
            for (int i =0 ;i<list.size()-1;i++){
                File file = new File(list.get(i));
                String fileName = new Date().getTime()+random.nextInt(100)+file.getName();
                uploadAliImg(fileName,list.get(i));
            }
        }else{
            //直接提交申诉内容
//            addAllege();
            showToast("请上传申诉图片");
        }
    }

    private List<String> mImageList = new ArrayList<>();
    private BaseSubscriber<Object> addAllegeSb;
    private void addAllege(){
        addAllegeSb = new BaseSubscriber<Object>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(Object o) {
                showToast("提交成功");
                setResult(RESULT_OK);
                finish();
            }
        };
        try{
            JSONObject jb = new JSONObject();
            JSONArray ja = new JSONArray();
            for (int i =0;i<mImageList.size();i++){
                ja.put(mImageList.get(i));
            }

            jb.put("content",inputMsgEt.getText().toString());
            jb.put("imgList",ja);
            jb.put("orderId",getIntent().getIntExtra("orderId",0));
            jb.put("userId", UserStringUtils.getUserId(mContext));
            Logger.d("参数："+jb.toString());


            ApiManager.getInstance().addAllege(addAllegeSb,jb.toString());
        }catch (Exception e){

        }
    }
}
